import { Message ,Loading} from 'element-ui'

var tipsShowTime = 2000

export default function ({ store, redirect, app: { $axios } }) {

  // Request拦截器：设置Token
//   $axios.onRequest((config) => {
//   })

$axios.onResponse((response) => {
    if(!process.client) {
      return response
    }
    const res = response.data;
    if(res.code == 200 && res.sucessTips != undefined && res.sucessTips.length>0) {
       Message({ message: res.sucessTips, type: 'success', duration: tipsShowTime });
       return response;
    }
    if(res.code == 210) { // 不需要任何提示的逻辑
        return response;
    }
    if (res.code !== 200) {
      var errorMsg = '未知错误，请联系管理员'
      var coustMessage = res.data.message
      if (coustMessage != undefined && coustMessage.length > 0) {
        errorMsg = res.data.message
      } else if (res.message.length > 0) {
        errorMsg = res.message
      }
      Message.closeAll()
      if(res.code == 996|| res.code == 999 || res.code == 998) {
        if (window != undefined) {
          window.localStorage.setItem('redclass_token', '')
          window.localStorage.setItem('redclass_user', '')
          window.$nuxt.$cookies.set('token', '')
        }
        if (res.code == 999 || res.code == 998) {
          window.$nuxt.$router.push({ name: 'user-login' });
        } else {
           window.loginInfo.showInfo();
           window.console.log(window.loginInfo);
        }
      }
      Message({ message: errorMsg, type: 'error', duration: tipsShowTime })
      return response;
    } else {
      return response;
    }
}),


 // Error拦截器：出现错误的时候被调用，根据状态码做对应判断并显示全局Message
$axios.onError((err) => {
    const code = parseInt(err.response && err.response.status)
    switch (code) {
        case 400:
          err.message = '请求错误(400)'
          break
        case 401:
          err.message = '未授权，请重新登录(401)'
          break
        case 403:
          err.message = '拒绝访问(403)'
          break
        case 404:
          err.message = '请求出错(404)'
          break
        case 408:
          err.message = '请求超时(408)'
          break
        case 500:
          err.message = '服务器错误(500)'
          break
        case 501:
          err.message = '服务未实现(501)'
          break
        case 502:
          err.message = '网络错误(502)'
          break
        case 503:
          err.message = '服务不可用(503)'
          break
        case 504:
          err.message = '网络超时(504)'
          break
        case 505:
          err.message = 'HTTP版本不受支持(505)'
          break
        default:
          err.message = `连接出错(${err.response.status})!`
    }
    Message.closeAll()
    Message({ message: err.message, type: 'error', tipsShowTime })
  })
}